const Base = require('../base.js');
const Core = require('@alicloud/pop-core'); // 阿里短信发送
const ali_sms = think.config('ali_sms')
const SMSClient = new Core({...ali_sms.Core});

var requestOption = { method: 'POST' };

module.exports = class extends Base {
  async indexAction() {
    let code = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);
    let phone = this.get('phone')
    if (!phone) return this.fail(-1, 'error')
    
    await this.session('sms_code', { phone, code, time: Date.now() + 300000 }); // 把验证码加入缓存 并设置验证码5分钟过期
    let result = {Code: 'Ok', sms_code: code}
    if (result.Code == 'Ok') {
      this.json({ status: 200, message: 'sussess', data: result })
    } else {
      this.fail(-1, result.Code || 'error', result)
    }
  }
  async indexActionBK() {
    let code = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);
    let phone = this.get('phone')
    if (!phone) return this.json({Code: 'error'})

    let params = {...ali_sms.params}
    params.PhoneNumbers = phone
    params.TemplateParam = JSON.stringify({code})

    let result
    try {
      result = await SMSClient.request('SendSms', params, requestOption)
      await this.session('sms_code', { phone, code, time: Date.now() + 300000 }); // 把验证码加入缓存 并设置验证码5分钟过期
    } catch (err) {
      console.log(err)
      result = {Code: 'error'}
    }
    if (result.Code == 'Ok') {
      this.json({ status: 200, message: 'sussess', data: result })
    } else {
      this.fail(-1, result.Code || 'error', result)
    }
  }
};
